<template>
  <div class="container">
    <div class="app-container">
      <el-row class="btn_container">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </el-row>
      <el-table v-loading="loading" :data="list">
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <span v-if="!row.isEdit">{{ row.name }}</span>
            <el-input v-else v-model="row.editRow.name" size="mini" placeholder="请输入角色名称" />
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template v-slot="{ row }">
            <!-- <template v-if="!row.isEdit"> {{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' :'无' }}</template> -->
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" size="mini" />
            <span v-else> {{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' :'无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <span v-if="!row.isEdit">{{ row.description }}</span>
            <el-input v-else v-model="row.editRow.description" type="textarea" size="mini" :rows="3" placeholder="请输入角色描述" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="handleAssignPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="确定要删除该数据吗" @onConfirm="confirmDel(row.id)">
                <template #reference>
                  <el-button style="margin-left: 10px" size="mini" type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-button size="mini" type="primary" @click="btneditOK(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="height:80px" type="flex" justify="end" align="middle">
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next, jumper, total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="roleForm.state" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK(row)">确定</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      width="500px"
      title="分配权限"
      :visible.sync="showAssignDialog"
      @close="showAssignDialog = false"
    >
      <el-tree
        ref="permissionTree"
        :data="permissionTreeData"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="{
          label: 'name',
          children: 'children'
        }"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnAssignRole">确定</el-button>
          <el-button size="mini" @click="showAssignDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleListAPI, assignRoleAPI, getRoleDetailAPI, getPermissionListAPI, addRoleAPI, updateRoleAPI, delRoleAPI } from '@/api'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      showDialog: false,
      loading: false,
      showPermissionDialog: false,
      permissionData: [],
      permissionTreeData: [],
      currentRoleId: null,
      showAssignDialog: false,
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      list: [],
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { rows, total } = await getRoleListAPI(this.pageParams)
      this.list = rows
      this.pageParams.total = total
      this.loading = false
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    async btnOK() {
      await this.$refs.roleForm.validate()
      await addRoleAPI(this.roleForm)
      this.$message.success('新增角色成功')
      this.close()
      this.getRoleList()
    },
    close() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
    },
    btnEditRow(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async btneditOK(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRoleAPI({
          id: row.id,
          ...row.editRow
        })
        this.$message.success('角色更新成功')
        Object.assign(row, { ...row.editRow, isEdit: false })
        this.row.isEdit = false
      } else {
        this.$message.warning('角色名称和描述不能为空')
      }
    },
    async confirmDel(id) {
      await delRoleAPI(id) // 删除的是后台数据
      this.$message.success('删除成功')
      if (this.list.length === 1) this.pageParams.page-- // 页码-1
      this.getRoleList()
    },
    async handleAssignPermission(id) {
      this.currentRoleId = id
      try {
        // 获取权限树数据
        const res = await getPermissionListAPI()
        this.permissionTreeData = transListToTreeData(res, 0) // 列表转化树形

        // 获取角色详情
        const roleDetail = await getRoleDetailAPI(id)
        const permIds = roleDetail.permIds || []

        // 显示弹窗并设置选中状态
        this.showAssignDialog = true // 渲染是异步的
        this.$nextTick(() => {
          this.$refs.permissionTree.setCheckedKeys(permIds) // 设置选中的key
        })
      } catch (error) {
        this.$message.error('获取权限数据失败')
      }
    },
    async btnAssignRole() {
      // 获取当前树组件选中的key
      await assignRoleAPI({ id: this.currentRoleId, permIds: this.$refs.permissionTree.getCheckedKeys() })
      this.showAssignDialog = false
      this.$message.success('分配权限成功')
    }
  }
}
</script>
<style scoped>
.btn_container {
  padding: 10px 20px;
}
</style>
